package com.stox.ui.javafx.list.widget.menu.item;

import java.util.Locale;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.stox.dto.AbstractModel;
import com.stox.dto.WatchList;
import com.stox.ui.javafx.list.client.WatchListClient;
import com.stox.ui.javafx.list.widget.WatchListTreeItem;
import com.stox.ui.javafx.list.widget.menu.WatchListContextMenu;
import com.stox.ui.javafx.list.widget.menu.WatchListMenu;

@Component
public class AddWatchListMenuItem extends MenuItem implements InitializingBean, EventHandler<ActionEvent> {

	@Autowired
	private ApplicationContext applicationContext;
	
	@Autowired
	private WatchListClient watchListClient;
	
	public AddWatchListMenuItem() {
		setOnAction(this);
	}
	
	@Override
	public void handle(ActionEvent arg0) {
		WatchListContextMenu watchListContextMenu = (WatchListContextMenu)getParentPopup(); 
		TreeView<AbstractModel> treeView = watchListContextMenu.getTreeView();
		TreeItem<AbstractModel> treeItem = treeView.getSelectionModel().getSelectedItem();
		TreeItem<AbstractModel> newTreeItem = applicationContext.getBean(WatchListTreeItem.class);
		WatchList newWatchList = createEmptyWatchList(treeItem.getValue().getId()); 
		newTreeItem.setValue(newWatchList);
		treeItem.getChildren().add(0, newTreeItem);
		treeItem.setExpanded(true);
		WatchListMenu menu = null;
		for(WatchListMenu watchListMenu : WatchListMenu.getWatchListMenus()){
			if(treeItem.getValue().getId().equals(watchListMenu.getWatchList().getId())){
				menu = watchListMenu;
				break;
			}
		}
		
		if(null != menu){
			WatchListMenu childMenu = applicationContext.getBean("watchListMenu",WatchListMenu.class);
			childMenu.setWatchList(newWatchList);
			menu.getItems().add(childMenu);
		}
	}
	
	private WatchList createEmptyWatchList(Long parentId){
		WatchList watchList = new WatchList();
		watchList.setName(applicationContext.getMessage("NewWatchList", null, Locale.getDefault()));
		watchList.setParentId(parentId);
		watchList.setId(watchListClient.save(watchList));
		return watchList;
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		setText(applicationContext.getMessage("AddWatchList", null, Locale.getDefault()));
	}

}

